import React, { useEffect, useMemo, useState } from "react";
import request from "../../api/request";
import { useNavigate, useSearchParams } from "react-router-dom";
import {
  InfiniteScroll,
  List,
  NavBar,
  Button,
  Selector,
  PullToRefresh,
} from "antd-mobile";
import Date from "../../compontent/Date";
import {
  RightOutline,
  MinusOutline,
  UserOutline,
  TeamOutline,
  UserAddOutline,
} from "antd-mobile-icons";

function Index() {
  let nav = useNavigate();
  let [list, setList] = useState([]);
  let [selQuery, setSelQuery] = useSearchParams();
  let [page, setPage] = useState(1);
  let [hasMoreData, setHasMoreData] = useState(true);
  let start = selQuery.get("start");
  let end = selQuery.get("end");
  let date = selQuery.get("date");

  let getData = async () => {
    try {
      let data = Object.fromEntries(selQuery);
      let res = await request.post("/api/trip/train", { ...data, page });

      if (res.data.data && res.data.data.length > 0) {
        setList((prev) => [...prev, ...res.data.data]);
        setPage((prev) => prev + 1);
      } else {
        setHasMoreData(false);
      }
    } catch (error) {
      console.error("获取数据失败:", error);
      setHasMoreData(false);
    }
  };

  useEffect(() => {
    setPage(1);
    setList([]);
    setHasMoreData(true); // 重置状态
    getData();
  }, [date, selQuery]);

  const FreshFn = async () => {
    try {
      const data = Object.fromEntries(selQuery);
      const res = await request.post("/api/trip/train", data);
      setList(res.data.data || []);
      setPage(1);
      setHasMoreData(res.data.data && res.data.data.length > 0); // 重置状态
    } catch (error) {
      console.error("刷新数据失败:", error);
    }
  };
  const xuan = async (value) => {
    if (value.includes("isgo")) {
      options[0].description = "耗时 短->长";
    } else {
      options[0].description = "出发 早->晚";
    }
    const obj = {
      isgo: false,
      iscar: false,
      istick: false,
    };
    value.forEach((item) => {
      obj[item] = true;
    });
    setSelQuery((prev) => {
      return { ...Object.fromEntries(prev), ...obj };
    });
    const data = { ...Object.fromEntries(selQuery), ...obj };
    const res = await request.post("/api/trip/train", data);
    setList(res.data.data);
    setPage(1);
  };
  const defaultSel=useMemo(()=>{
    let temp=[];
    ['isgo','iscar','istick'].forEach((item)=>{
      if(selQuery.get(item)==='true'){
        temp.push(item)
      }
    });
    if(selQuery.get('isgo')==='true'){
      options[0].description='耗时 短->长'
    }
    return temp
  },[selQuery])
  const xing=(item)=>{
    nav(`/detail/${item.id}?start=${item.startStation}&end${item.endStation}&date=${date}`)
  }
  const options = [
    {
      label: <UserOutline />,
      description: "出发 -早-晚",
      value: "isgo",
    },
    {
      label: <TeamOutline />,
      description: "只看高铁动车",
      value: "iscar",
    },
    {
      label: <UserAddOutline />,
      description: "只看有票",
      value: "istick",
    },
  ];

  return (
    <div>
      <NavBar onBack={() => nav(-1)}>
        <div className="kp">
          {start} <MinusOutline /> <RightOutline /> {end}
        </div>
        <Date date={date} />
      </NavBar>
      <div>
        <PullToRefresh onRefresh={() => FreshFn()}>
          <table>
            <tbody>
              {list.length > 0 &&
                list.map((item, ind) => (
                  <tr key={ind} onClick={()=>xing(item)}>
                    <td>发车 {item.startTime}</td>
                    <td>{item.startStation}</td>
                    <td>{item.trainNo}</td>
                    <td>￥{item.ssoftSeat.price}</td>
                    <td>到达 {item.endTime}</td>
                    <td>{item.endStation}</td>
                    <td>耗时 {item.timeTaken}</td>
                    <td>
                      二等座：{item.ssoftSeat.ticketNum}
                      {typeof item.ssoftSeat.ticketNum === "number" ? "张" : ""}
                    </td>
                  </tr>
                ))}
            </tbody>
          </table>
        </PullToRefresh>
      </div>

      <InfiniteScroll loadMore={getData} hasMore={hasMoreData} />
      <div adm-selector>
        <Selector
          columns={3}
          options={options}
          defaultValue={defaultSel}
          multiple
          onChange={(value) => xuan(value)}
        />
      </div>
    </div>
  );
}

export default Index;
